package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.ProductStock;
import cn.wolfcode.wms.domain.SaleAccount;
import cn.wolfcode.wms.domain.StockOutcomeBill;
import cn.wolfcode.wms.domain.StockOutcomeBillItem;
import cn.wolfcode.wms.mapper.ProductStockMapper;
import cn.wolfcode.wms.mapper.SaleAccountMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillItemMapper;
import cn.wolfcode.wms.mapper.StockOutcomeBillMapper;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IStockOutcomeBillService;
import cn.wolfcode.wms.utils.PageResult;
import cn.wolfcode.wms.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class StockOutcomeBillServiceImpl implements IStockOutcomeBillService {

    @Autowired
    private StockOutcomeBillMapper mapper;
    @Autowired
    private StockOutcomeBillItemMapper stockOutcomeBillItemMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    @Autowired
    private SaleAccountMapper saleAccountMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        stockOutcomeBillItemMapper.deleteByPrimaryKey(id);

        mapper.deleteByPrimaryKey(id);

    }

    @Override
    public void insert(StockOutcomeBill entity) {

        //先保存出库单据
        entity.setStatus(StockOutcomeBill.STATUS_NOMAL);
        entity.setInputTime(new Date());
        entity.setInputUser(UserContext.getEmployee());
        BigDecimal totalNumber = BigDecimal.ZERO;

        BigDecimal totalAmount = BigDecimal.ZERO;

        List<StockOutcomeBillItem> items = entity.getItems();
        for (StockOutcomeBillItem item : items) {

            //计算总数量
            totalNumber = totalNumber.add(item.getNumber());
            //计算总额
            totalAmount = totalAmount.add(item.getNumber().multiply(item.getSalePrice()));
        }

        entity.setTotalNumber(totalNumber);
        entity.setTotalAmount(totalAmount);
        mapper.insert(entity);

        //保存出库单明细
        for (StockOutcomeBillItem item : items) {
            //设置出库单的id
            item.setBillId(entity.getId());
            item.setAmount(item.getNumber().multiply(item.getSalePrice()));
            stockOutcomeBillItemMapper.insert(item);
        }


    }

    @Override
    public StockOutcomeBill selectByPrimaryKey(Long id) {
        System.out.println(mapper);
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<StockOutcomeBill> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public void updateByPrimaryKey(StockOutcomeBill entity) {

        StockOutcomeBill old = mapper.selectByPrimaryKey(entity.getId());
        //当其状态为0时此时才可以更新数据
        if (old.getStatus() == StockOutcomeBill.STATUS_NOMAL) {
            //先保存出库单据
            entity.setStatus(StockOutcomeBill.STATUS_NOMAL);
            entity.setInputTime(new Date());
            entity.setInputUser(UserContext.getEmployee());
            BigDecimal totalNumber = BigDecimal.ZERO;

            BigDecimal totalAmount = BigDecimal.ZERO;

            List<StockOutcomeBillItem> items = entity.getItems();
            for (StockOutcomeBillItem item : items) {
                //保存明细
                item.setBillId(entity.getId());
                item.setAmount(item.getNumber().multiply(item.getSalePrice()));
                stockOutcomeBillItemMapper.insert(item);


                //计算总数量
                totalNumber = totalNumber.add(item.getNumber());
                //计算总额
                totalAmount = totalAmount.add(item.getNumber().multiply(item.getSalePrice()));

            }

            entity.setTotalNumber(totalNumber);
            entity.setTotalAmount(totalAmount);
            mapper.updateByPrimaryKey(entity);

        }
    }

    @Override
    public PageResult query(QueryObject qo) {
        System.out.println("StockOutcomeBillServiceImpl.query");
        Long totalCount = mapper.queryForCount(qo);
        if (totalCount == 0) {
            return new PageResult(qo.getPageSize());
        }
        List<StockOutcomeBill> listData = mapper.queryForList(qo);
        return new PageResult(listData, totalCount, qo.getCurrentPage(), qo.getPageSize());
    }

    /**
     * 出库单审核之后商品得出库
     * @param id
     */
    @Override
    public void audit(Long id) {
        //从数据库查询出该id值单据的审核状态,如果已经审核,则没必要审核 审核就出库
        StockOutcomeBill bill = mapper.selectByPrimaryKey(id);
        if (bill.getStatus() == StockOutcomeBill.STATUS_NOMAL) {
            //此状态为未审核
            //审核人
            bill.setAuditor(UserContext.getEmployee());
            //审核时间
            bill.setAuditTime(new Date());
            //审核状态
            bill.setStatus(StockOutcomeBill.STATUS_AUDIT);
            mapper.audit(bill);
            //审核完之后出库
            List<StockOutcomeBillItem> items = bill.getItems();
            for (StockOutcomeBillItem item : items) {
                ProductStock ps = productStockMapper.selectByProductIdAndDepotId(item.getProduct().getId(),bill.getDepot().getId());
                if(ps == null){

                    throw  new RuntimeException("商品["+item.getProduct().getName()+"]在["+bill.getDepot().getName()+"]中不存在");

                }
                if(ps.getStoreNumber().compareTo(item.getNumber()) < 0){
                    throw  new RuntimeException("商品["+item.getProduct().getName()+"]在["+bill.getDepot().getName()+"]中库存量不足"+item.getNumber());

                }

                //减少库存
                ps.setStoreNumber(ps.getStoreNumber().subtract(item.getNumber()));
                ps.setAmount(ps.getPrice().multiply(ps.getStoreNumber()));
                productStockMapper.updateByPrimaryKey(ps);

                //在出库成功之后需要生成一个账
                SaleAccount account = new SaleAccount();
                account.setClient(bill.getClient());
                account.setProduct(item.getProduct());
                account.setVdate(bill.getVdate());
                account.setNumber(item.getNumber());

                account.setCostPrice(item.getProduct().getCostPrice());
                account.setSalePrice(item.getSalePrice());

                account.setCostAmount(account.getNumber().multiply(account.getCostPrice())
                .setScale(2, RoundingMode.HALF_UP));
                account.setSaleAmount(item.getAmount());

                saleAccountMapper.insert(account);
            }


        }




    }


}
